const Koa = require('koa');
const app = new Koa();
const bodyparser = require('koa-bodyparser');

app.use(bodyparser());

app.use(async(ctx)=>{
    if(ctx.url === '/' && ctx.method === 'GET') {
        //显示表单页面
        let html = `
            <h1>XGP</h1>
            <form method="post" action="/">
                <label>userName</label><input name="username"><br>
                <label>age</label><input name="age"><br>
                <label>website</label><input name="website"><br>
                <button type="submit">提交</button>
            </form>
        `;
        ctx.body = html;
    }else if(ctx.url === '/' && ctx.method === 'POST') {
        // let postData = await parsePostData(ctx);
        let postData = ctx.request.body;
        ctx.body = postData;
    }else {
        ctx.body = "404!";
    }
});

function parsePostData(ctx) {
    return new Promise((resolve,reject) => {
        try {
            let postData = "";
            ctx.req.addListener("data",(data) => {
                postData += data;
            });
            ctx.req.on("end",function () {
                let parseData = parseQueryStr(postData);
                resolve(parseData);
            })
        }catch (e) {
            reject(e);
        }
    });
}

function parseQueryStr(queryStr) {
    let queryData = {};
    let queryStrList = queryStr.split('&');
    for (let [index,queryStr] of queryStrList.entries()) {
        let itemList = queryStr.split('=');
        queryData[itemList[0]] = decodeURIComponent(itemList[1]);
    }
    return queryData;
}

// 监听端口
app.listen(3000,() => {
    //监听回调
    console.log('app is start at port 3000');
});
